package com.tezign.intelligence.mini.dam.aifamilyconsultant.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.ResponseBean;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.UserLastQuestionDelReq;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.UserLastQuestionReq;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.resp.UserSessionQuestionSuggestionVO;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.resp.UserSessionQuestionVO;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.FamilyMember;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.UserSessionQuestion;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.UserSessionQuestionSuggest;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.FamilyStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.UserStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IFamilyMemberService;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IUserSessionQuestionService;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IUserSessionQuestionSuggestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author six
 * @since 2025-01-11
 */
@Api(tags = "会话建议")
@Slf4j
@CrossOrigin("*")
@RestController
@RequiredArgsConstructor
@RequestMapping(Constant.APPLICATION_NAME + "/userSessionQuestionSuggest")
public class UserSessionQuestionSuggestController {

    private final IUserSessionQuestionService userSessionQuestionService;

    private final IFamilyMemberService familyMemberService;

    private final IUserSessionQuestionSuggestService userSessionQuestionSuggestService;

    private final RedisTemplate<String, String> redisTemplate;


    public static final String CACHE_KEY_QUEST_LAST_ID = "question.last.id:%s_%s";


    // 获取最后回答的问题id
    @GetMapping("/getLastQuestionId")
    public ResponseBean<Long> getLastQuestionId(@RequestParam("userId") Long userId, @RequestParam("userSessionId") Long userSessionId) {
        String lastQuestionIdStr = redisTemplate.opsForValue().get(String.format(CACHE_KEY_QUEST_LAST_ID, userId, userSessionId));
        return new ResponseBean<Long>().success(Objects.isNull(lastQuestionIdStr) ? null : Long.valueOf(lastQuestionIdStr));
    }


    // 设置最后回答的问题id
    @PostMapping("/saveLastQuestionId")
    public ResponseBean<Boolean> saveLastQuestionId(@RequestBody @Valid UserLastQuestionReq req) {
        redisTemplate.opsForValue().set(String.format(CACHE_KEY_QUEST_LAST_ID, req.getUserId(), req.getUserSessionId()), String.valueOf(req.getLastQuestionId()));
        return new ResponseBean<Boolean>().success(true);
    }


    // 删除最后回答的问题id
    @PostMapping("/deleteLastQuestionId")
    public ResponseBean<Boolean> deleteLastQuestionId(@RequestBody @Valid UserLastQuestionDelReq req) {
        redisTemplate.delete(String.format(CACHE_KEY_QUEST_LAST_ID, req.getUserId(), req.getUserSessionId()));
        return new ResponseBean<Boolean>().success(true);
    }

    // 获取建议列表
    @GetMapping("/list")
    @ApiOperation(value = "获取会话建议列表")
    public ResponseBean<List<UserSessionQuestionVO>> list() {
        ResponseBean<List<UserSessionQuestionVO>> res = new ResponseBean<>();
        FamilyMember familyMember = familyMemberService.lambdaQuery().eq(FamilyMember::getUserId, UserStore.getUserId()).eq(FamilyMember::getFamilyId, FamilyStore.getFamilyId()).last("limit 1").one();
        if (familyMember == null) {
            throw new RuntimeException("当前用户不在家庭中");
        }
        String role = familyMember.getRole();
        List<UserSessionQuestion> userSessionQuestions = userSessionQuestionService.lambdaQuery().eq(UserSessionQuestion::getRole, role).orderByAsc(UserSessionQuestion::getSort).list();
        if (CollUtil.isEmpty(userSessionQuestions)) {
            return res;
        }
        List<Long> questionIdList = userSessionQuestions.stream().map(UserSessionQuestion::getId).collect(Collectors.toList());
        List<UserSessionQuestionSuggest> list = userSessionQuestionSuggestService.lambdaQuery().in(UserSessionQuestionSuggest::getUserSessionQuestionId, questionIdList).orderByAsc(UserSessionQuestionSuggest::getSort).list();

        if (CollUtil.isEmpty(list)) {
            return res;
        }
        Map<Long, List<UserSessionQuestionSuggest>> questionSuggetionMap = list.stream().collect(Collectors.groupingBy(UserSessionQuestionSuggest::getUserSessionQuestionId));
        List<UserSessionQuestionVO> data = userSessionQuestions.stream().map(x -> {
            UserSessionQuestionVO userSessionQuestionVO = new UserSessionQuestionVO();
            userSessionQuestionVO.setQuestionId(x.getId());
            userSessionQuestionVO.setQuestion(x.getQuestion());
            userSessionQuestionVO.setQuestionType(x.getQuestionType());
            userSessionQuestionVO.setRole(x.getRole());

            List<UserSessionQuestionSuggest> suggestList = questionSuggetionMap.get(x.getId());
            if(CollUtil.isNotEmpty(suggestList)) {
                List<UserSessionQuestionSuggestionVO> suggestVos = suggestList.stream().map(po -> BeanUtil.copyProperties(po, UserSessionQuestionSuggestionVO.class)).collect(Collectors.toList());
                userSessionQuestionVO.setSuggestionList(suggestVos);
            }
            return userSessionQuestionVO;
        }).collect(Collectors.toList());
        return res.success(data);
    }
}
